package com.defysoft.waukids.intro;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Intro_Yacguan;
import com.defysoft.waukids.R;

public class Intro_Login_A extends BaseActivity implements OnClickListener {
	String uuid = "";
	private SharedPreferences member;
	private SharedPreferences school;
	EditText id;
	EditText ps;
	AlertDialog alert;
	private final int RESEND_SUCCESS= 5;
	private final int FINDID_CLICK = 6;
	private final int SELECT_STARTACTIVITY = 7;
	private final int LOGIN_FAIL = 8;
	private final int JOIN_CLICK = 9;
	private final int LOGIN_CLICK = 10;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == INTRO_JOIN_TO_LOGIN) {
			showPopup("가입성공", "가입시 입력한 E-mail형식의\n아이디로 인증 메일이\n발송 되었습니다.\n메일 인증 후 로그인 하세요.", 0);
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro__login_);
		setStartData();
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		uuid = getIntent().getStringExtra(INTENT_EXTRA_INTRO_UUID);
		id = (EditText) findViewById(R.id.INTRO_ID_ET);
		ps = (EditText) findViewById(R.id.INTRO_PS_ET);
		member = getSharedPreferences("member", MODE_PRIVATE);
		school = getSharedPreferences("school", MODE_PRIVATE);
		id.setText(member.getString("PK_Mem_Email", ""));
		findViewById(R.id.INTRO_LOGIN_BTN).setOnClickListener(this);
		findViewById(R.id.INTRO_JOIN_BTN).setOnClickListener(this);
		findViewById(R.id.INTRO_JOIN_FINDID).setOnClickListener(this);
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		if (firstThread != null) {
			firstThread.interrupt();
		}
		switch (choice) {
		case 1:
			firstThread = new Thread(new Runnable() {
				@Override
				public void run() {
					mainThread();
				}
			});
			break;
		case 2:
			firstThread = new Thread(new Runnable() {
				@Override
				public void run() {
					reSendThread();
				}
			});
			break;
		}
		
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG).show();
			break;
		case LOGIN_CLICK:
			if (id.getText().length() == 0) {
				Toast.makeText(this, "이메일을 입력하세요", Toast.LENGTH_LONG).show();
			} else if (ps.getText().length() == 0) {
				Toast.makeText(this, "비밀번호를 입력하세요", Toast.LENGTH_LONG).show();
			} else {
				startNetwork(1);
			}
			break;
		case JOIN_CLICK:
			startActivityForResult(new Intent(this, Intro_Join_A.class).putExtra(INTENT_EXTRA_INTRO_UUID, uuid), INTRO_LOGIN_TO_JOIN);
			break;
		case FINDID_CLICK:
			startActivity(new Intent(this, Intro_FindId_A.class));
			break;
		case LOGIN_FAIL:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		case SELECT_STARTACTIVITY:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			if (!member.getString("Mem_Confirm", "0").equals("1")) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Intro_Login_A.this);
				builder.setMessage("아직 메일인증이 되지 않은 가입정보입니다.")
						.setCancelable(false)
						.setPositiveButton("인증메일 다시보내기",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										startNetwork(2);
									}
								})
						.setNegativeButton("종료",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				alert = builder.create();
				alert.show();
			} else if (member.getString("Mem_Rank", "0").equals("3")) {// 부모일경우
				startActivity(new Intent(this, Intro_SelectStudent_A.class));
				finish();
			} else if (member.getString("Mem_Rank", "0").equals("0")) {// 아직
																		// 유치원등록되지
																		// 않은
																		// 원장선생님
				Toast.makeText(this, "아직 유치원에 연결되지 않은 원장정보입니다. 관리자에 문의해주세요",Toast.LENGTH_LONG).show();
			} else if (member.getString("Mem_Rank", "0").equals("2") // 아직반등록이
																		// 안된
																		// 선생님
					&& member.getString("FK_Cla_Mem_Code", "0").equals("0")) {
				Toast.makeText(this, "아직 유치원반에 연결되지 않은 선생님정보입니다. 관리자에 문의해주세요",Toast.LENGTH_LONG).show();
			} else if (!member.getString("Mem_Rank", "0").equals("0")) {// 원장&선생님경우
				startActivity(new Intent(this, Intro_Main_A.class));
				finish();
			}

			else {
				Toast.makeText(this, "회원정보에 문제가 있거나 내부오류입니다.",Toast.LENGTH_LONG).show();
			}
			break;
			
			case RESEND_SUCCESS :
				endDIal();
				if (firstThread != null) {
					firstThread.interrupt();
				}
				Toast.makeText(this, "메일발송 완료",Toast.LENGTH_LONG).show();
				alert.dismiss();
			break;
			
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.INTRO_LOGIN_BTN:
			sendMessage(LOGIN_CLICK);
			break;
		case R.id.INTRO_JOIN_BTN:
			sendMessage(JOIN_CLICK);
			break;
		case R.id.INTRO_JOIN_FINDID:
			sendMessage(FINDID_CLICK);
			break;
		}
	}

	private void setPreferencesMember(String msg) {
		try {
			JSONObject jsonObject = new JSONObject(msg);
			SharedPreferences.Editor editora = member.edit();
			editora.putString("PK_Mem_Email",
					jsonObject.getString("PK_Mem_Email"));
			editora.putString("Mem_Pass", ps.getText().toString());
			editora.putString("FK_Sch_Mem_Code",
					jsonObject.getString("FK_Sch_Mem_Code"));
			editora.putString("FK_Cla_Mem_Code",
					jsonObject.getString("FK_Cla_Mem_Code"));
			editora.putString("Mem_Phone", jsonObject.getString("Mem_Phone"));
			editora.putString("Mem_Name", jsonObject.getString("Mem_Name"));
			editora.putString("Mem_CreateDate",
					jsonObject.getString("Mem_CreateDate"));
			editora.putString("Mem_Uuid", jsonObject.getString("Mem_Uuid"));
			editora.putString("Mem_Rank", jsonObject.getString("Mem_Rank"));
			editora.putString("Mem_Connect",
					jsonObject.getString("Mem_Connect"));
			editora.putString("Mem_Birth", jsonObject.getString("Mem_Birth"));
			editora.putString("Mem_Confirm",
					jsonObject.getString("Mem_Confirm"));
			editora.commit();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "member" + e.toString());
		}
		;
	}

	private void setPreferencesSchool(String msg) {
		try {
			JSONObject jsonObject = new JSONObject(msg);

			SharedPreferences.Editor editora = school.edit();
			editora.putString("PK_Sch_Code",
					jsonObject.getString("PK_Sch_Code"));
			editora.putString("FK_Add_Sch_Code",
					jsonObject.getString("FK_Add_Sch_Code"));
			editora.putString("Sch_Name", jsonObject.getString("Sch_Name"));
			editora.putString("Sch_Add", jsonObject.getString("Sch_Add"));
			editora.putString("Sch_Info", jsonObject.getString("Sch_Info"));
			editora.commit();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "school" + e.toString());
		}
		;
	}

	private void mainThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_LOGIN_CHECK, "uuid=" + uuid + "&email="
							+ id.getText().toString() + "&pass="
							+ ps.getText().toString()));
			if (jsonObject.getBoolean("success")) {
				setPreferencesMember(jsonObject.getString("payload")); // 맴버정보.
				if (jsonObject.getString("sch") != "false") {
					setPreferencesSchool(jsonObject.getString("sch")); // 학원정보.
				}
				onNetworkCallback(SELECT_STARTACTIVITY, "");
			} else {
				onNetworkCallback(LOGIN_FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}
	//뒤로두번눌렀을때.
	private boolean mPressFirstBackKey = false;
	private Timer timer;
	@Override
	public void onBackPressed() {
		if (mPressFirstBackKey == false) {	// 백키 첫번째
			Toast.makeText(this, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
			mPressFirstBackKey = true;
			TimerTask second = new TimerTask() {
				@Override
				public void run() {
					timer.cancel();
					timer = null;
					mPressFirstBackKey = false;
				}
			};
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			timer = new Timer();
			timer.schedule(second, 2000);
		} else {
			super.onBackPressed();
		}
	}
	
	private void reSendThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_RESENDMAIL, "&email=" + id.getText().toString()));
			if (jsonObject.getBoolean("success")) {
				
				onNetworkCallback(RESEND_SUCCESS, "");
			} else {
				onNetworkCallback(LOGIN_FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}
}
